﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using vconf_shared;

namespace vconf_server
{
    static class State
    {
        static private Dictionary<String, User> activeUsers = new Dictionary<string, User>();

        static public bool RegisterUser(User user)
        {
            if (!activeUsers.ContainsKey(user.Name))
            {
                activeUsers.Add(user.Name, user);
                return true;
            }
            else
            {
                return false;
            }
        }

        static public bool UnregisterUser(User user)
        {
            if (activeUsers.ContainsKey(user.Name))
            {
                activeUsers.Remove(user.Name);
                return true;
            }
            else
            {
                return false;
            }
        }

        static public bool AssignStreamURL(User user, String url)
        {
            if (activeUsers.ContainsKey(user.Name))
            {
                User u = activeUsers[user.Name];
                u.StreamURL = url;
                return true;
            }
            else
            {
                return false;
            }
        }

        static public bool UpdateHeartbeatTime(User user)
        {
            if (activeUsers.ContainsKey(user.Name))
            {
                User u = activeUsers[user.Name];
                u.LastHeartbeat = DateTime.Now;
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Unregisters users which haven't send a heartbeat for the past 10 seconds.
        /// </summary>
        /// <returns>The number of users that have been unregistered.</returns>
        static public int ClearInactiveUsers()
        {
            int usersUnregisteredCount = 0;
            TimeSpan allowedInactivity = new TimeSpan(0, 0, 10);
            foreach (KeyValuePair<string, User> pairUser in activeUsers)
            {
                if (DateTime.Now - pairUser.Value.LastHeartbeat > allowedInactivity)
                {
                    State.UnregisterUser(pairUser.Value);
                    Console.WriteLine("[DEBUG] User: " + pairUser.Value.Name + " dropped due to inactivity");
                }
            }
            Console.WriteLine("[DEBUG] Inactivity check finished: " + usersUnregisteredCount + " out of " + State.activeUsers.Count + " users dropped");
            return usersUnregisteredCount;
        }

        static public Dictionary<String, User> GetUsers()
        {
            return activeUsers;
        }
    }
}
